"use client";
import { useEffect, useState } from "react";
import { CartesianGrid, Line, LineChart, XAxis } from "recharts";

import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  ChartConfig,
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
} from "@/components/ui/chart";
import { IGoods } from "../columns";
export interface IChartsData {
  month: string;
  shopName: string;
  shopPrice: number;
  platformPrice: number;
}
const chartConfig = {
  shopName: {
    label: "商家",
    color: "var(--chart-1)",
  },
  shopPrice: {
    label: "商家价格",
    color: "var(--chart-2)",
  },
  platformPrice: {
    label: "平台价格",
    color: "var(--chart-3)",
  },
} satisfies ChartConfig;
interface ChartPageProps {
  title: string;
  data: IGoods[];
}
export interface IShopChartData {
  date: string;
  shopName: string;
  shopPrice: number;
  platformPrice: number;
}
export function ChartsPage({ title, data }: ChartPageProps) {
  const [chartsData, setChartsData] = useState<IShopChartData[]>([]);
  const [tickMargin, setTickMargin] = useState(2);
  useEffect(() => {
    const dd = data.map((v: IGoods): IShopChartData => {
      const dt = new Date(v.updateTime);
      const updateTime = `${dt.getDate()}`;
      return {
        date: updateTime,
        shopName: v.shopName,
        shopPrice: v.shopPrice,
        platformPrice: v.platformPrice,
      };
    });
    setTickMargin(dd.length + 2);
    setChartsData(dd);
  }, [data]);
  return (
    <Card>
      <CardHeader>
        <CardTitle>Line Chart - Multiple</CardTitle>
        <CardDescription>{title}</CardDescription>
      </CardHeader>
      <CardContent>
        <ChartContainer config={chartConfig}>
          <LineChart
            accessibilityLayer
            data={chartsData}
            margin={{
              left: 12,
              right: 12,
            }}
          >
            <CartesianGrid vertical={false} />
            <XAxis
              dataKey="date"
              tickLine={false}
              axisLine={false}
              tickMargin={tickMargin}
              tickFormatter={(value) => value}
            />
            <ChartTooltip cursor={false} content={<ChartTooltipContent />} />
            <Line
              dataKey="shopName"
              type="monotone"
              strokeWidth={2}
              dot={false}
            />
            <Line
              dataKey="shopPrice"
              type="monotone"
              strokeWidth={2}
              dot={false}
            />
            <Line
              dataKey="platformPrice"
              type="monotone"
              strokeWidth={2}
              dot={false}
            />
          </LineChart>
        </ChartContainer>
      </CardContent>
      <CardFooter></CardFooter>
    </Card>
  );
}
